import { createStore } from 'vuex'
// 设置localStorage.cartList方法
const setLocalCart = (state) => {
  const string = JSON.stringify(state);
  localStorage.cartList = string;
}
// 设置localStorage.address方法
const setLocalAddress=(state)=>{
  const string = JSON.stringify(state);
  localStorage.address = string;
}
// 获取localStorage.cartList方法
const getLocalCart = () => {
  try {
    return  JSON.parse(localStorage.cartList);
  } catch(e) {
    return {}
  }
}
// 获取localStorage.address方法
const getLocalAddress=()=>{
  try {
    return  JSON.parse(localStorage.address);
  } catch(e) {
    return {}
  }
}

export default createStore({
  state: {
    // 设置购物车cartList和地址address数据
    cartList: getLocalCart() ,
    address:getLocalAddress(),
  },
  mutations: {
    changeItemToCart(state, payload) {
      const { shopId, productId, productInfo, num, shopName } = payload;
      let shopInfo = state.cartList[shopId] || { shopName, productList: {} };
      let product = shopInfo.productList[productId];
      if (!product) {
        product = productInfo;
        product.count = 0;
        product.check = false;
      }
      product.count += num;
      if (product.count <= 0) {
        product.count = 0;
        product.check = false;
      }
      shopInfo.productList[productId] = product;
      state.cartList[shopId] = shopInfo;
      setLocalCart(state.cartList);
    },
    // 改变商品选中
    changeChecked(state, payload) {
      const { shopId, productId } = payload;
      const product = state.cartList[shopId].productList[productId];
      product.check = !product.check;
      setLocalCart(state.cartList);
    },
    // 清除所有被选中商品
    clearChecked(state, payload) {
      const { shopId } = payload;
      state.cartList[shopId].productList = {};
      setLocalCart(state.cartList);
    },
    // 选取所有添加的商品
    checkAll(state, payload) {
      const { shopId } = payload;
      const products = state.cartList[shopId].productList;
      for (let k in products) {
        products[k].check = true;
      }
      setLocalCart(state.cartList);
    },
    // 获取从模拟接口传递过来的地址信息赋值给state.address
    getAddress(state,payload){
      const {newAddress}=payload;
      state.address=[];
      for(let i=0;i<newAddress.length;i++) {
        state.address.push(newAddress[i]);
      }
      console.log(state.address);
      setLocalAddress(state.address);
    }
  },
  actions: {
  },
  modules: {
  }
})
